using DG.Tweening;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Share.UI
{
    //¿Ø¼þ½¥Èë½¥³ö
    public class UIEffect_Fade : UIEffectBase
    {
        private Dictionary<Graphic, float> m_OriginalAlphas = new Dictionary<Graphic, float>();

        [SerializeField]
        float m_Duration = 0.5f;


        // Start is called before the first frame update
        void Start()
        {
        }

        // Update is called once per frame
        void Update()
        {

        }

        private void OnEnable()
        {
            //OnActionEnter();
        }

        public override void OnActionEnter()
        {
            FadeTo(1, true);
        }

        void FadeTo(float value, bool fadeIn)
        {
            var images = GetComponentsInChildren<Image>();
            var texts = GetComponentsInChildren<Text>();
            var allGraphics = new List<Graphic>();
            allGraphics.AddRange(images);
            allGraphics.AddRange(texts);

            // 保存原始alpha值
            foreach (var graphic in allGraphics)
            {
                if (!m_OriginalAlphas.ContainsKey(graphic))
                {
                    m_OriginalAlphas[graphic] = graphic.color.a;
                }
            }

            // 设置初始状态
            foreach (var graphic in allGraphics)
            {
                var color = graphic.color;
                color.a = fadeIn ? 0 : m_OriginalAlphas[graphic];
                graphic.color = color;
            }

            // 延迟执行动画
            DOVirtual.DelayedCall(m_fDelay, () =>
            {
                foreach (var graphic in allGraphics)
                {
                    float targetAlpha = fadeIn ? m_OriginalAlphas[graphic] : 0;
                    graphic.DOFade(targetAlpha, m_Duration);
                }
            });
        }

        public override void DoActionExit()
        {
            FadeTo(0, false);
        }
    }
}
